<?php
/**
 * LoginController.php
 * 登录相关
 * @author Life <349865361@qq.com>
 * @version 20140109
 */
class LoginController extends AdminController
{
    /**
     * 登录页面
     */
    public function index()
    {
        $key = $_GET['key'];
        if(empty($key)){
            $this->msg('无法获取您的登录KEY！', 0);
        }
        $config = config('APP');
        $safeKey = md5($config['SAFE_KEY']);
        if($key <> $safeKey){
            $this->msg('登录KEY错误，请勿非法登录！', 0);
        }
        $this->assign('safeKey', $safeKey);
        $this->assign('adminInfo', config('ADMIN'));
        $this->display();
    }
    /**
     * 登录提交
     * @param string $_POST['username'] 用户名
     * @param string $_POST['password'] 密码
     */
    public function postLogin()
    {
        $_POST = in($_POST);
        $key = $_POST['key'];
        if(empty($key)){
            $this->msg('无法获取您的登录KEY！', 0);
        }
        $config = config('APP');
        $safeKey = md5($config['SAFE_KEY']);
        if($key <> $safeKey){
            $this->msg('登录KEY错误，请勿非法登录！', 0);
        }
        $userName = $_POST['username'];
        $passWord = $_POST['password'];
        if (empty($userName) || empty($passWord)) {
            $this->msg('帐号信息输入错误!', false);
        }
        //获取帐号信息
        $info = model('User')->getUserInfo($userName);
        //进行帐号验证
        if (empty($info)) {
            $this->msg('登录失败! 无此用户帐号!', false);
        }
        if ($info['password'] != md5($passWord)) {
            $this->msg('登录失败! 密码错误!', false);
        }
        if ($info['status'] == 0) {
            $this->msg('登录失败! 该用户已被禁用!', false);
        }
        //获取用户组信息
        $infoGroup = model('UserGroup')->getInfo($info['group_id']);
        if (empty($infoGroup)) {
            $this->msg('用户组不存在！', false);
        }
        $info['group_level'] = $infoGroup['level'];
        $info['group_name'] = $infoGroup['name'];
        //更新帐号信息
        $data['last_login_time'] = time();
        $data['last_login_ip'] = get_client_ip();
        $data['login_num'] = intval($info['login_num']) + 1;
        $data['user_id'] = $info['user_id'];
        model('User')->saveData($data);
        //更新登录记录
        $logData = $info;
        $logData['type'] = 1;
        model('UserLog')->addData($logData);
        //设置登录信息
        $info['admin'] = $infoGroup['admin'];
        $this->setLogin($info);
        $this->msg('登录成功!', 1);
    }
    //退出
    public function logout()
    {
        $this->clearLogin(url('default/Index/index'));
    }
}